package net.flyinggroup.gateway.config;

import net.flyinggroup.spring.gateway.security.oauth2.reactive.TokenRelayWithRefreshGatewayFilterFactory;
import org.springframework.cloud.gateway.filter.factory.SpringCloudCircuitBreakerFilterFactory;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.cloud.security.oauth2.gateway.TokenRelayGatewayFilterFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 网关相关的路由配置，也可以通过application.yaml进行配置。
 *
 * @author walker
 * @since 0.0.1
 */
@Configuration
public class RouteConfig {
    private SpringCloudCircuitBreakerFilterFactory circuitBreakerFilterFactory;
    private TokenRelayWithRefreshGatewayFilterFactory tokenRelayGatewayFilterFactory;

    public RouteConfig(SpringCloudCircuitBreakerFilterFactory circuitBreakerFilterFactory, TokenRelayWithRefreshGatewayFilterFactory tokenRelayGatewayFilterFactory) {
        this.circuitBreakerFilterFactory = circuitBreakerFilterFactory;
        this.tokenRelayGatewayFilterFactory = tokenRelayGatewayFilterFactory;
    }

    @Bean
    public RouteLocator customerRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes()
                .route("car", predicateSpec -> predicateSpec.path("/cars")
                        .filters(fn -> fn.filters(circuitBreakerFilterFactory.apply(config -> config.setName("carFallback").setFallbackUri("forward:/car-fallback"))))
                        .uri("lb://car"))
                .route("hotels-service", predicateSpec -> predicateSpec.path("/hotels/**")
                        .filters(fn -> fn.filters(tokenRelayGatewayFilterFactory.apply()))
                        .uri("http://localhost:38082/"))
                .build();
    }
}